package org.streets.workflow.engine.extension;

import org.streets.workflow.engine.WorkflowEngine;
import org.streets.workflow.engine.WorkflowException;
import org.streets.workflow.engine.ISyncRouter;
import org.streets.workflow.engine.IToken;
import org.streets.workflow.engine.entities.ProcessInstance;
import org.streets.workflow.engine.event.NodeEvent;
import org.streets.workflow.engine.mem.EndNode;
import org.streets.workflow.engine.persistence.IWorkflowDAO;

/**
 *
 */
public class EndNodeExtension extends SyncRouterExtension {

    public String getExtentionPointName() {
        return EndNode.ExtensionPointNodeEventListener;
    }

    public String getExtentionTargetName() {
        return EndNode.ExtensionTargetName;
    }

    public void onNodeEventFired(WorkflowEngine engine, NodeEvent event)
            throws WorkflowException {
    	
    	//同步器节点的监听器触发条件，是在离开这个节点的时候
        if (event.getEventType() == NodeEvent.NODEINSTANCE_LEAVING) {
            ISyncRouter syncInst = (ISyncRouter) event.getSource();
            IWorkflowDAO persistence = engine.getRuntimeContext().getPersistenceService();
            //删除同步器节点的token
            persistence.deleteTokens(event.getToken().getProcess().getId(), syncInst.getNodeId());
        }    	
    	//如果节点实例结束，就触发
        if (event.getEventType() == NodeEvent.NODEINSTANCE_COMPLETED) {
            // 执行ProcessInstance的complete操作
            IToken token = event.getToken();            
            ProcessInstance currentProcessInstance = (ProcessInstance) token.getProcess();
            engine.complete(currentProcessInstance);
        }
    }
}
